package com.emm.yixun.soap.util.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;

/* *
 * 工具类
 *
 */

public class RequestUtil {

	public static final int CONNECT_TIME_OUT = 40000;

	public static final int TIME_OUT = 40000;


	/**
	 * 建立请求，以模拟远程HTTP的POST请求方式构造
	 * @throws HttpException
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws IllegalArgumentException
	 * @throws GeneralSecurityException
	 * @throws Exception
	 */
	public static String buildRequest(String url, Map<String, String> sParaTemp,String inputCharset) throws HttpException, UnsupportedEncodingException,
			GeneralSecurityException {
		try {
			HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
			HttpRequest request = new HttpRequest(HttpResultType.BYTES);
			// 设置编码集
			request.setCharset(inputCharset);
			request.setMethod(HttpRequest.METHOD_POST);
			request.setConnectionTimeout(CONNECT_TIME_OUT);
			request.setTimeout(TIME_OUT);
			request.setParameters(generatNameValuePair(sParaTemp));
			request.setUrl(url);
			HttpResponse response = httpProtocolHandler.execute(request, null, null);
			if (response == null) {
				return null;
			}
			return URLDecoder.decode(response.getStringResult(), inputCharset);
		} catch (UnsupportedEncodingException e) {
			throw e;
		} catch (HttpException e) {
			throw new HttpException("network transport error or protocal error");
		} catch (SocketTimeoutException e) {
			throw new HttpException("server response time out");
		} catch (IOException ex) {
		}
		return null;
	}

	/**
	 * MAP类型数组转换成NameValuePair类型
	 * 
	 * @param properties
	 *            MAP类型数组
	 * @return NameValuePair类型数组
	 */
	private static NameValuePair[] generatNameValuePair(Map<String, String> properties, String charset)
			throws UnsupportedEncodingException {
		NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
		int i = 0;
		for (Map.Entry<String, String> entry : properties.entrySet()) {
			if(StringUtils.isNotBlank(charset)){
				nameValuePair[i++] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), charset));
			}else{
				nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
			}
			
		}

		return nameValuePair;
	}
	
	private static NameValuePair[] generatNameValuePair(Map<String, String> properties)
			throws UnsupportedEncodingException {
		NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
		int i = 0;
		for (Map.Entry<String, String> entry : properties.entrySet()) {
			nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
		}
		return nameValuePair;
	}
	

}
